package com.demo.study.reflection;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @author Baymax
 * @since 2021/10/10
 */
public class Demo03 {
    public static void main(String[] args) throws Exception {
        User user = new User();
        Class<? extends User> userClass = user.getClass();

        Field[] fields = userClass.getFields();
        if (fields.length > 0) {
            for (Field field : fields) {
                System.out.println(field);
            }
        }
        System.out.println("----------------------------");
        Field[] declaredFields = userClass.getDeclaredFields();
        if (declaredFields.length > 0) {
            for (Field declaredField : declaredFields) {
                System.out.println(declaredField);
            }
        }
        System.out.println("----------------------------");
        Field name = userClass.getDeclaredField("name");
        System.out.println(name);
        name.setAccessible(true);
        name.set(user, "zhangsan");
        System.out.println(name.get(user)); // 返还该字段在实体对象上的值
        System.out.println("----------------------------");

        Method eatM = userClass.getDeclaredMethod("eat", String.class);
        eatM.setAccessible(true);
        eatM.invoke(user, "香蕉");

        Method playM = userClass.getDeclaredMethod("play");
        playM.setAccessible(true);
        Object result = playM.invoke(user);
        System.out.println(result.toString());

    }
}
